﻿/**************************************************************************
创建日期:	2019/7/18 8:53:49     
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com
创建时间:	
Copyright (c)  ZhCun.cn

描	述：
记	录：
***************************************************************************/
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text;
using ZhCun.Utils;
using ZhCun.WebCommon.FormatJson;

namespace ZhCun.WebCommon
{
    public class GlobalExceptionsFilter : IExceptionFilter
    {
        private readonly IHostingEnvironment _Environment;

        public GlobalExceptionsFilter(IHostingEnvironment environment)
        {
            this._Environment = environment;
        }

        public void OnException(ExceptionContext context)
        {
            Exception exception = context.Exception;
            string error = string.Empty;

            void ReadException(Exception ex)
            {
                error += string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
                if (ex.InnerException != null)
                {
                    ReadException(ex.InnerException);
                }
            }

            LogHelper.LogObj.Error(exception.InnerException);

            ReadException(context.Exception);

            ContentResult result = new ContentResult
            {
                StatusCode = 500,
                ContentType = "text/json;charset=utf-8;"
            };

            if (_Environment.IsDevelopment())
            {
                var json = new { message = exception.Message, detail = error };
                result.Content = json.ToJson();
            }
            else
            {
                result.Content = "抱歉，出错了";
            }
            context.Result = result;
            context.ExceptionHandled = true;
        }
    }
}
